from hjl_spider.download.HTTP import HttpResponse
from hjl_spider.download.base import DownloadBase
import aiohttp
import asyncio


class AioHttpRequest(object):
    def __init__(self, url: str, session: aiohttp.ClientSession, method="GET", move="parse", headers=None,
                 params=None, data=None, proxy=None, **kwargs):
        '''
        :param url:
        :param move: 转移函数
        :param headers: 请求头
        :param params:  请求参数
        :param data:  表单参数
        :param proxy: 代理
        '''

        self.session = session
        self.url = url
        self.method = method
        self.move = move
        self.headers = headers
        self.params = params
        self.data = data
        self.proxy = proxy

    def download(self):
        if self.method.upper() == "GET":  # 判断请求类型
            async with await self.session.get(url=self.url, params=self.params, headers=self.headers) as res:
                response = HttpResponse(self.url, await res.text(), self.move, res.status, await res.read())

        elif self.method.upper() == "POST":  # POST
            async with await self.session.post(url=self.url, data=self.data, headers=self.headers) as res:
                response = HttpResponse(self.url, await res.text(), self.move, res.status, await res.read())

        return response  # 返回response

